package org.leetcode.middle.leetcode148;

import org.leetcode.easy.ListNode;

public class Solution3 {
    public ListNode sortList(ListNode head) {

        ListNode res = split(head, null);

        return res;
    }

    private ListNode split(ListNode head, ListNode tail) {

        if (head == null) {
            return head;
        }

        if (head.next == tail) {
            head.next = null;
            return head;
        }

        ListNode slow = head;
        ListNode fast = head;

        while (fast != tail) {
            fast = fast.next;
            slow = slow.next;
            if (fast != tail) {
                fast = fast.next;
            }
        }

        ListNode mid = slow;

        ListNode left = split(head, mid);
        ListNode right = split(mid, tail);

        return merge(left, right);
    }

    private ListNode merge(ListNode left, ListNode right) {
        ListNode dummy = new ListNode(-1);
        ListNode list = dummy;

        while (left != null && right != null) {
            if (left.val > right.val) {
                list.next = right;
                right=right.next;
            }else {
                list.next=left;
                left=left.next;
            }
            list = list.next;
        }

        if (left==null){
            list.next=right;
        }

        if (right==null){
            list.next=left;
        }

        return dummy.next;
    }
}
